import axios from 'axios';
import store from 'store';
import { customHistory } from './history';
import { logout } from 'store/actions';
import { message } from 'antd';
const http = axios.create({
  baseURL: 'http://toutiao.itheima.net/v1_0',
  timeout: 50000,
});
http.interceptors.request.use((config) => {
  // 获取token
  const { login: token } = store.getState();
  // 除了登录请求外，其他请求统一添加 token
  if (!config.url.startsWith('/authorizations')) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});
http.interceptors.response.use(undefined, (error) => {
  if (error.response) {
    message.error('网络繁忙，请稍后再试');
    return Promise.reject(error);
  }
  if (error.response.status === 401) {
    message.error(error.response.data.message);
    // 删除token
    store.dispatch(logout());
    // 跳转到登录页，并携带当前要访问的页面，这样，登录后可以继续返回该页面
    customHistory.push('/login', {
      from: customHistory.location.pathname,
    });
  }
  return Promise.reject(error);
});
export { http };
